﻿define([
    'Xjs/core/util',
    'Xjs/core/builder',
    'Xjs/ui/Container',
    'Xjs/ui/tool/Collapser'
],
function (util, builder, Container) {
    'use strict';

    var type = 'treeNode',
    TreeNode = Xjs.getType(type);

    if (TreeNode) { // It has been already loaded
        return TreeNode;
    }

    var createTreeNode = function (host, conf) {

        var iconElement,
        outerContent = Xjs.create('control', {
            attributes: {
                cls: 'w-treeNodeOuterContent'
            },
        }, host),
        innerContent;

        if (conf.leaf) {

            iconElement = Xjs.create('content', {
                cls: 'w-tool ' + (conf.iconCls || 'w-iconCls') // Replace any existing classes of the control
            }, outerContent);

            outerContent.addChild(iconElement);
        }
        else { // Create a collapser to collapse or expand the tree

            host.collapser = Xjs.create('collapser', {
                collapsedCls: conf.collapsedCls || host.collapsedCls,
                expandedCls: conf.expandedCls || host.expandedCls,
                targets: host.children
            }, outerContent);

            outerContent.addChild(host.collapser);
        }

        innerContent = Xjs.create('control', {
            attributes: {
                cls: 'w-treeNodeInnerContent'
            },
            content: host.content || conf.label,
            tooltip: conf.tooltip,
            highlightable: conf.highlightable || host.highlightable,
            selectable: conf.selectable || host.selectable
        }, outerContent);

        outerContent.addChild(innerContent);

        host.content = outerContent;
    };

    TreeNode = util.define({
        base: Container,
        construct: function (conf, parent) {

            TreeNode.base.constructor.call(this, conf, parent); // Call the base constructor

            createTreeNode(this, conf);
        },
        type: type,
        defaultChildType: 'treeNode',
        highlightable: true,
        selectable: true

        // The default class for the collapsed icon tree
        //collapsedCls: 'collpasedTreeNode',

        // The default class for the expanded icon tree
        //expandedCls: 'expandedTreeNode',
    });

    Xjs.registerType(TreeNode);

    return TreeNode;
});